package com.feihong.yw189.activity.dingdan;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SDCardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.WebInterface.AjaxWebInterface;
import com.feihong.yw189.activity.WebInterface.OrderDetailWebInterface;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.kaika.SelectNumActivity;
import com.feihong.yw189.activity.kuandai.ChooseSimKaActivity;
import com.feihong.yw189.activity.kuandai.HengXiangSign;
import com.feihong.yw189.activity.kuandai.ZuoJiActivity;
import com.feihong.yw189.activity.tiaoxingma.TiaoXingMaActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.http.FileUploader;
import com.feihong.yw189.http.FileUploaderCallBack;
import com.feihong.yw189.http.Host;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.http.ZhiWenTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.DingDan.AddPhotoModel;
import com.feihong.yw189.model.DingDan.DetailSubmitPhotoNumModel;
import com.feihong.yw189.model.DingDan.PayMoneyModel;
import com.feihong.yw189.model.Kaika.KaiKaSubmitkaihuModel;
import com.feihong.yw189.model.Kaika.UpLoadPicModel;
import com.feihong.yw189.utils.ComPareUtils;
import com.feihong.yw189.utils.CustomServiceUtil;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.PhotoUtils;
import com.feihong.yw189.utils.ToolsUtil;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.utils.WebViewClientRToken;
import com.feihong.yw189.view.WebView4Scroll;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.just.agentweb.AgentWeb;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import txgw.feihong.com.txgwlibrary.mqglide_loader.MQGlideImageLoader4;

import static com.feihong.yw189.activity.kaika.ChooseTaoCanActivity.KAIKA_SELECT_PACAKGE_GROUPID_KEY;
import static com.feihong.yw189.activity.kaika.SelectNumActivity.AL_SELECT_TEL_NUM_KEY;
import static com.feihong.yw189.activity.kaika.SelectNumActivity.KAIKA_NUM_LEV_MEMO;
import static com.feihong.yw189.activity.kaika.SelectNumActivity.KAIKA_PHONE_NUM_KEY;
import static com.feihong.yw189.activity.kaika.SelectNumActivity.KAIKA_PHONE_TYPE;
import static com.feihong.yw189.activity.kuandai.ChooseSimKaActivity.SELECT_SIM_NUM_KEY;
import static com.feihong.yw189.activity.kuandai.ZuoJiActivity.SELECT_FIXPHONE_NUM_ID_KEY;
import static com.feihong.yw189.activity.kuandai.ZuoJiActivity.SELECT_FIXPHONE_NUM_KEY;

@RuntimePermissions
public class DingDanDetailsActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_goback)
    RelativeLayout rlGoback;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;
    private boolean fist_One = false;
    private Unbinder unbinder;
    private String orderInfo;


    /**
     * 弹出自定义键盘
     **/
    private String orderSn;

    private String keyWordOrderSn;
    private String keyWordUrl;
    private String specGId;
    private static final int DETAILSPHONENUMBER_REQUEST_CODE = 651;
    private static final int DETAILS_CHANGESIM_REQUEST_CODE = 652;
    private static final int DETAILS_FUKA_REQUEST_CODE = 657;
    private static final int DETAILS_CHANGE_ZUOJI_REQUEST_CODE = 653;
    private static final int KAIKA_SELECT_PHONE_NUM_REQUEST = 654;
    private static final int KAIKA_SELECT_FUKA_REQUEST = 656;
    private static final int HANDSIGN_SELECT_REQUEST = 655;
    private static final int HANDSIGN_GETQIANMING_REQUEST = 611;
    private String oldIccid;
    private String oldOrderTel;
    BaseBottomDialog dialog = null;
    private String type_img;
    private String mcallBack;
    private String handsigntype;
    private String KKAIKA_orBUKA;

    /*拍照*/
    private Uri imageUri;
    private File fileUri = null;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private int photoType = 0; //0拍照 1相册
    private String PicType;
    private String appPhotoUrl;
    private String orderPhone;
    private Intent mInetent;
    private String stringExtra;
    private File file_wenjian = null;
    private String updownpic_url;
    private String updownpic_Repurl;

    private ArrayList<String> imageList;//图片列表
    private static byte step = 1;//更多跳转
    MyUsualyDialog mYdialog;
    private String callBackCount;
    private String order_phone;
    DJLM_PasswordDialog pwdDialog;
    private String req_transid;

    private String webCallBackFuncName = "";

    private  String mCreateAccountUrl ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_webview);
        unbinder = ButterKnife.bind(this);
        stringExtra = getIntent().getStringExtra("title");
        mYdialog = new MyUsualyDialog(this, R.layout.wait_item);

        imageList = new ArrayList<String>();//图片列表

        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }


    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    public void initView() {
        setBackButtonFinish();
        if (TextUtils.isEmpty(stringExtra)) {
            setPageTitle("订单详情");
        } else {
            setPageTitle(stringExtra);
        }
        ivLin.setVisibility(View.VISIBLE);
        orderSn = getIntent().getStringExtra("order_sn");
        orderInfo = getIntent().getStringExtra("orderInfo");
        req_transid = getIntent().getStringExtra("req_transid");

        // AgentWeb 保持了 WebView 的使用 ，
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        mswiperefreshlayout.setOnRefreshListener(() -> bindData());
        mswiperefreshlayout.setRefreshing(false);
    }

    private void bindData() {
        Long time = MyLoginUtils.getCuurrentTime();
        String signStr = new ComPareUtils.ComPareBuilder()
                .put("order_sn", orderSn)
                .put("time", String.valueOf(time))
                .create().getSignString();
        if (mAgentWeb == null) {
            WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mswiperefreshlayout);
            webView4Scroll.setVerticalScrollBarEnabled(false);
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(webviewFrame, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebView(webView4Scroll)
                    .setWebViewClient(mWebViewClient)
                    .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(HttpTools.HTTP_HOME + orderInfo + "?token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken() + "&sign=" + signStr + "&order_sn=" + orderSn + "&time=" + time + "&version=" + "and." + AppUtils.getAppVersionName());

            mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);
            // mAgentWeb.getAgentWebSettings().getWebSettings().setJavaScriptEnabled(true); // 张鹏加的，还未测试

            //屏蔽长按弹出复制按钮
           /* mAgentWeb.getWebCreator().get().setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });*/
        } else {
            mAgentWeb.getWebCreator().getWebView().setVisibility(View.VISIBLE);
            mAgentWeb.getUrlLoader().reload();
        }
        ivLin.setOnClickListener(v -> {
            CustomServiceUtil customServiceUtil = new CustomServiceUtil();
            MQImage.setImageLoader(new MQGlideImageLoader4());
            Intent customeServiceIntent = new MQIntentBuilder(getApplication())
                    .setClientInfo(customServiceUtil.queryConfig())
                    .build();
            startActivity(customeServiceIntent);
        });
        mAgentWeb.getWebCreator().getWebView().setVisibility(View.VISIBLE);
        jsCallJava();

    }

    private WebViewClient mWebViewClient = new WebViewClientRToken() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("Order/kaika_info.html")) {
                step = 2;
                setPageTitle("号码订单详情");
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (mswiperefreshlayout != null) {
                mswiperefreshlayout.postDelayed(() -> mswiperefreshlayout.setRefreshing(false), 300);
            }
            if (fist_One != true) {
                if (!TextUtils.isEmpty(req_transid)) {
                    fist_One = true;
                    mAgentWeb.getJsAccessEntrace().quickCallJs("progress", req_transid);
                }
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };

    @Override
    @OnClick({R.id.iv_back, R.id.rl_goback})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_goback:
                finish();
                break;
            case R.id.user_take_photo:
                //拍照
                photoType = 0;
                DingDanDetailsActivityPermissionsDispatcher.NeedPermissionWithCheck((DingDanDetailsActivity) getActivity());

                dialog.dismiss();
                break;
            case R.id.user_select_from_lib:
                //相册
                photoType = 1;
                DingDanDetailsActivityPermissionsDispatcher.NeedPermissionWithCheck((DingDanDetailsActivity) getActivity());
                dialog.dismiss();
                break;
            case R.id.user_photo_cancel:
                //取消
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    private void jsCallJava() {

        //添加Ajax数据请求的接口
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AjaxWebInterface.AJAX_KEY, new AjaxWebInterface(this, mAgentWeb.getJsAccessEntrace()));

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new OrderDetailWebInterface(mAgentWeb, DingDanDetailsActivity.this, new ActionCallBack() {

            @Override
            public void saoma(String funcName) {
                // showInfoToast(funcName);
                webCallBackFuncName = funcName;
                Intent intent = new Intent(getActivity(), TiaoXingMaActivity.class);
                startActivityForResult(intent, TiaoXingMaActivity.REQ_CODE);
            }

            @Override
            public String getToken() {
                String token = UserLoginInfo.getUserLoginInfoInstance().getUserToken();
                return token;
            }

            /*------sign---------*/
            @Override
            public String sendSign(String info) {
                try {
                    JSONObject json = new JSONObject();
                    Map<String, String> map = new HashMap<>();
                    long time = MyLoginUtils.getCuurrentTime();
                    map.put("time", "" + time);
                    json.put("sign", "" + ToolsUtil.getsignRes(info, map));
                    json.put("time", TimeUtils.getNowMills() / 1000 + "");
                    return json.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "error";
                }
            }

            /*------支付---------*/
            @Override
            public String orderPay(String info) {
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    keyWordUrl = (String) jsonObject.optString("url");
                    keyWordOrderSn = (String) jsonObject.optString("order_sn");
                    String payType = jsonObject.optString("type");
                    if(payType.equals("kuandai")){
                        mCreateAccountUrl = HttpTools.BR_CREATEACCOUNT_URL;
                    }else {
                        mCreateAccountUrl = HttpTools.KK_CREATEACCOUNT_URL;
                    }
                    showKeyBoard();
                } catch (Exception e) {
                }
                return "";
            }

            /*------获取订单补传照片----宽带-----*/
            @Override
            public String setDzda(String info) {
                fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/takepic.jpg");
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    appPhotoUrl = jsonObject.optString("url");
                    keyWordOrderSn = jsonObject.optString("order_sn");
                    PicType = jsonObject.optString("type");
                    type_img = jsonObject.optString("type_img");
                } catch (Exception e) {
                }
                KKAIKA_orBUKA = "1";
                if (type_img.equals("1")) {
                    DingDanDetailsActivityPermissionsDispatcher.NeedPermissionWithCheck(DingDanDetailsActivity.this);

                } else if (type_img.equals("2")) {
                    PhotoUtils.openPic(getActivity(), CODE_GALLERY_REQUEST);
                } else if (type_img.equals("3")) {
                    dialogChoose();
                }
                return "";
            }

            /*------获取宽带手机号号---------*/
            @Override
            public String setPhone(String info) {
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    appPhotoUrl = jsonObject.optString("url");
                    keyWordOrderSn = jsonObject.optString("order_sn");
                    orderPhone = jsonObject.optString("order_phone");
                    specGId = jsonObject.optString("group_id");
                    order_phone = jsonObject.optString("order_phone");
                    String type_url = jsonObject.optString("type_url");
                    if (type_url.equals("kd")) {
                        mInetent = new Intent(DingDanDetailsActivity.this, SelectNumActivity.class);
                        ArrayList<String> arrayList = new ArrayList<>();
                        arrayList.add(orderPhone);
                        mInetent.putExtra(SelectNumActivity.PHONE_NUM_REQUEST_URL, HttpTools.GET_KUANDAI_NUM);
                        mInetent.putExtra(KAIKA_SELECT_PACAKGE_GROUPID_KEY, specGId);
                        mInetent.putStringArrayListExtra(AL_SELECT_TEL_NUM_KEY, arrayList);
                        startActivityForResult(mInetent, DETAILSPHONENUMBER_REQUEST_CODE);
                    } else {
                        mInetent = new Intent(DingDanDetailsActivity.this, SelectNumActivity.class);
                        mInetent.putExtra(SelectNumActivity.PHONE_NUM_REQUEST_URL, HttpTools.GET_KK_NUM);
                        mInetent.putExtra(KAIKA_SELECT_PACAKGE_GROUPID_KEY, specGId);
                        startActivityForResult(mInetent, KAIKA_SELECT_PHONE_NUM_REQUEST);
                    }
                } catch (Exception e) {
                }
                return "";
            }


            @Override
            public String get_phone(String info) {
                try {
                    Log.i(TAG, "get_phone: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    callBackCount = jsonObject.optString("callback");
                    specGId = jsonObject.optString("spec_g_id");
                    if (!TextUtils.isEmpty(specGId)) {
                        mInetent = new Intent(DingDanDetailsActivity.this, SelectNumActivity.class);
                        mInetent.putExtra(SelectNumActivity.PHONE_NUM_REQUEST_URL, HttpTools.GET_KK_NUM);
                        mInetent.putExtra(KAIKA_SELECT_PACAKGE_GROUPID_KEY, specGId);
                        startActivityForResult(mInetent, KAIKA_SELECT_FUKA_REQUEST);
                    }
                } catch (Exception e) {
                }
                return "";
            }

            /*------获取宽带iCCID号---------*/
            @Override
            public String setIccid(String info) {
                try {
                    Log.i(TAG, "setIccid: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    appPhotoUrl = jsonObject.optString("url");
                    keyWordOrderSn = jsonObject.optString("order_sn");
                    oldIccid = jsonObject.optString("order_iccid");


                    mInetent = new Intent(DingDanDetailsActivity.this, ChooseSimKaActivity.class);
                    ArrayList<String> arrList = new ArrayList<>();
                    arrList.add(oldIccid);
                    mInetent.putStringArrayListExtra("simList", arrList);
                    mInetent.putExtra("position", "0988");
                    startActivityForResult(mInetent, DETAILS_CHANGESIM_REQUEST_CODE);

                } catch (Exception e) {
                }
                return "";
            }

            /*------获取宽副 iCCID号---------*/
            @Override
            public String get_iccid(String info) {
                try {
                    Log.i(TAG, "get_iccid: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    callBackCount = jsonObject.optString("callback");
                    specGId = jsonObject.optString("duan");


                    mInetent = new Intent(DingDanDetailsActivity.this, ChooseSimKaActivity.class);
                    ArrayList<String> arrList = new ArrayList<>();
                    arrList.add(oldIccid);
                    mInetent.putStringArrayListExtra("simList", arrList);
                    mInetent.putExtra("position", "0988");
                    startActivityForResult(mInetent, DETAILS_FUKA_REQUEST_CODE);

                } catch (Exception e) {
                }
                return "";
            }


            /*------座机号---------*/
            @Override
            public String setTel(String info) {
                try {
                    Log.i(TAG, "setTel: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    appPhotoUrl = jsonObject.optString("url");
                    keyWordOrderSn = jsonObject.optString("order_sn");
                    oldOrderTel = jsonObject.optString("order_tel");

                    String segm_id = jsonObject.optString("segm_id");
                    String acc_type = jsonObject.optString("acc_type");
                    String dire_no = jsonObject.optString("dire_no");

                    if (TextUtils.isEmpty(dire_no)) {
                        mInetent = new Intent(DingDanDetailsActivity.this, ZuoJiActivity.class);
                        mInetent.putExtra("acc_type", acc_type);
                        mInetent.putExtra("segm_id", segm_id);
                        startActivityForResult(mInetent, DETAILS_CHANGE_ZUOJI_REQUEST_CODE);
                    } else if (!TextUtils.isEmpty(dire_no)) {
                        mInetent = new Intent(DingDanDetailsActivity.this, ZuoJiActivity.class);
                        mInetent.putExtra("dire_no", dire_no);
                        startActivityForResult(mInetent, DETAILS_CHANGE_ZUOJI_REQUEST_CODE);
                    }
                } catch (Exception e) {
                }
                return "";
            }

            /*------手写  签名---------*/
            @Override
            public String setQianming(String info) {
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    appPhotoUrl = jsonObject.optString("url");
                    keyWordOrderSn = jsonObject.optString("order_sn");
                    handsigntype = jsonObject.optString("type");

                    mInetent = new Intent(DingDanDetailsActivity.this, HengXiangSign.class);
                    ArrayList<String> arrList = new ArrayList<>();
                    arrList.add(oldIccid);
                    mInetent.putExtra("position", "1127");
                    startActivityForResult(mInetent, HANDSIGN_SELECT_REQUEST);

                } catch (Exception e) {
                }
                return "";
            }

            /*------手写  签名---------*/
            @Override
            public String get_qianming(String info) {
                try {
                    JSONObject jsonObject = new JSONObject(info);

                    //  keyWordOrderSn = jsonObject.optString("order_sn");
                    handsigntype = jsonObject.optString("type");
                    mcallBack = jsonObject.optString("callback");

                    mInetent = new Intent(DingDanDetailsActivity.this, HengXiangSign.class);
                    ArrayList<String> arrList = new ArrayList<>();
                    arrList.add(oldIccid);
                    mInetent.putExtra("position", "1127");
                    startActivityForResult(mInetent, HANDSIGN_GETQIANMING_REQUEST);

                } catch (Exception e) {
                }
                return "";
            }

            /*------预览图片---------*/
            @Override
            public String images_zoom(String info) {
                Log.i(TAG, "images_zoom: " + info);
                    mInetent = new Intent(DingDanDetailsActivity.this, ImageBroawseActivity.class);
                    mInetent.putExtra("img", info);
                    startActivity(mInetent);
                return null;
            }

            /*------预览图片---------*/
            @Override
            public String progress(String info) {
                if (!TextUtils.isEmpty(req_transid)) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("progress", req_transid);
                }
                return "";
            }


            /*------相机  开卡回调---------*/
            @Override
            public Boolean get_images(String info) {
                fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/takepic.jpg");
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    type_img = jsonObject.optString("type");
                    mcallBack = jsonObject.optString("callback");
                    appPhotoUrl = jsonObject.optString("url");
                } catch (Exception e) {
                }
                KKAIKA_orBUKA = "0";
                if (type_img.equals("1")) {
                    takePhotoImage(0);
                } else if (type_img.equals("2")) {
                    takePhotoImage(1);
                } else if (type_img.equals("3")) {
                    dialogChoose();
                }
                return false;
            }

        }));


    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void NeedPermission() {
        switch (photoType) {
            case 0:
//                takePhoto();
                openCamera();
                break;
            case 1:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DingDanDetailsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onShowRationale(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", (dialog, which) ->
                        request.proceed())
                .setNegativeButton("拒绝", (dialog, which) ->
                        request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onPermissionDenied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskAgin() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    public interface ActionCallBack {

        void saoma(String funcName);

        String getToken();

        String sendSign(String info);

        String orderPay(String info);

        String setDzda(String info);

        String setPhone(String info);

        String get_phone(String info);

        String setIccid(String info);

        /**  获取宽副 iCCID号  **/
        String get_iccid(String info);

        String setTel(String info);

        String setQianming(String info);

        String get_qianming(String info);

        /**
         * 预览图片
         */
        String images_zoom(String info);

        /**
         * 调进度条
         */
        String progress(String info);

        /**
         * 拍照
         * @param info
         * @return
         */
        Boolean get_images(String info);

    }

    /**   键盘     */
    private void showKeyBoard() {

        if (pwdDialog != null && pwdDialog.isAdded()) {
            pwdDialog.dismiss();
        }

        pwdDialog = new DJLM_PasswordDialog(DingDanDetailsActivity.this);
        pwdDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, final String pwd) {
                pwdDialog.showLoadingView();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //orderSn, orderInfo
                        subOrderNet(pwd, keyWordUrl, keyWordOrderSn, "", "");
                    }
                }, 1000);
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
                pwdDialog.showLoadingView();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String random = ZhiWenTools.getRandNum();
                        String pwd = ZhiWenTools.getZhiWenPwd(random);
                        String touch_pwd = ZhiWenTools.getZhiWebKey();
                        subOrderNet(pwd, keyWordUrl, keyWordOrderSn, touch_pwd, random);
                    }
                }, 1000);
            }

            @Override
            public void onBtnClick(int type) {
                if(type == 3){
                    pwdDialog.dismiss();
                }
            }
        });
        if (ZhiWenTools.isSupportZhiWenPay(pwdDialog)) {
            pwdDialog.setEnableFinger(true);
        } else {
            pwdDialog.setEnableFinger(false);
        }
        pwdDialog.show(getSupportFragmentManager(), "支付键盘");
        //pwdDialog.setEnableFinger(false);//关闭指纹支付功能，只用密码支付

    }


    /*  支付密码  请求*/
    private void subOrderNet(final String password, final String keyWordUrl, String keyWordOrderSn, String touch_pwd, String randomNum) {
        App.getApp().getHttpTools().getKaiKaPassWorld(keyWordOrderSn,password,  touch_pwd, randomNum, keyWordUrl,new RequestCallBack<String>() {
//
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    PayMoneyModel payMoneyModel = JSON.parseObject(result, PayMoneyModel.class);
                    if (payMoneyModel != null) {
                        if (payMoneyModel.getStatus() == 1) {

                            pwdDialog.setState(R.mipmap.pay_su, "" + payMoneyModel.getInfo());
                            mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 1000);

                            String auth_kaihu = String.valueOf(payMoneyModel.getData().getAuth_kaihu());
                            if (!TextUtils.isEmpty(auth_kaihu) && auth_kaihu.equals("1")) {
                                App.getApp().getHttpTools().getKaiKaKaiHu(orderSn,mCreateAccountUrl, new RequestCallBack<String>() {
                                    @Override
                                    public void onSuccess(String result) {
                                        KaiKaSubmitkaihuModel model = JSON.parseObject(result, KaiKaSubmitkaihuModel.class);
                                        if (model.getStatus() == 1) {
                                            mAgentWeb.getJsAccessEntrace().quickCallJs("progress", String.valueOf(model.getData().getReq_transid()));
                                        } else {
                                            showToast("" + model.getInfo());
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                        showToast(getResources().getString(R.string.connect_sever_error_toast));
                                    }

                                    @Override
                                    public void onCancelled(Callback.CancelledException cex) {
                                    }

                                    @Override
                                    public void onFinished() {
                                    }
                                });
                            } else {
                                showToast("" + payMoneyModel.getInfo());
                                mAgentWeb.getUrlLoader().reload();
                            }
                        } else {
                            pwdDialog.setState(R.mipmap.pay_er, "" + payMoneyModel.getInfo());
                            mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 3000);
                        }
                    } else {
                        if (pwdDialog != null && pwdDialog.isAdded()) {
                            pwdDialog.dismiss();
                        }
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                    if (pwdDialog != null && pwdDialog.isAdded()) {
                        pwdDialog.dismiss();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (pwdDialog != null ) {
                    pwdDialog.dismiss();
                }
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    //拍照相册选择dialog
    private void dialogChoose() {
        dialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.activity_my_photo_edit)
                .setDimAmount(0.5f)
                // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)
                // 点击外部区域是否关闭，默认true
                .setTag("BottomDialog")
                // 设置DialogFragment的tag
                .setViewListener(new BottomDialog.ViewListener() {
                    // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View v) {
                        dialogClick(v);
                    }
                })
                .show();
    }

    private void dialogClick(View v) {
        v.findViewById(R.id.user_take_photo).setOnClickListener(this);
        v.findViewById(R.id.user_select_from_lib).setOnClickListener(this);
        v.findViewById(R.id.user_photo_cancel).setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case TiaoXingMaActivity.REQ_CODE:
                    if (data != null) {
                        String iccid = data.getStringExtra(TiaoXingMaActivity.INTENT_ICCID);
                        if (TextUtils.isEmpty(iccid) || TextUtils.isEmpty(webCallBackFuncName)) {
                            return;
                        }
                        if (mAgentWeb == null) {
                            return;
                        }
                        mAgentWeb.getJsAccessEntrace().callJs(webCallBackFuncName + "('" + iccid + "')");
                    }
                    return;
                case CODE_CAMERA_REQUEST:
                    //拍照完成回调
                    if (KKAIKA_orBUKA.equals("0")) {
                        if (fileUri != null) {
                            file_wenjian = new File(fileUri.getAbsolutePath());
                            if (file_wenjian != null || file_wenjian.exists()) {
                                submitPic();
                            } else {
                                showToast("请拍照上传身份证");
                                return;
                            }
                        }
                    } else if (KKAIKA_orBUKA.equals("1")) {
                        if (fileUri != null) {
                            file_wenjian = new File(fileUri.getAbsolutePath());
                            if (file_wenjian != null || file_wenjian.exists()) {
                                submitKuanDaiPic();
                            } else {
                                showToast("请拍照上传身份证");
                                return;
                            }
                        }
                    }
                    break;
                case CODE_GALLERY_REQUEST:
                    Uri resultUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (fileUri != null) {
                        file_wenjian = new File(resultUri.getPath());
                        if (file_wenjian != null || file_wenjian.exists()) {
                            submitKuanDaiPic();
                        } else {
                            showToast("请拍照上传身份证");
                            return;
                        }
                    }
                    break;
                case DETAILSPHONENUMBER_REQUEST_CODE:
                    //选手机号返回的结果KAIKA_PHONE_NUM_KEY
                    String phoneNum = data.getStringExtra(KAIKA_PHONE_NUM_KEY);
                    //手机号
                    String numLevMemo = data.getStringExtra(KAIKA_NUM_LEV_MEMO);
                    String typePhone = data.getStringExtra(KAIKA_PHONE_TYPE);
                    submitPhoneNumber(specGId, phoneNum, numLevMemo, typePhone);
                    break;
                case KAIKA_SELECT_PHONE_NUM_REQUEST:
                    String NumPhone = data.getStringExtra(KAIKA_PHONE_NUM_KEY);
                    String mPhoneNumID = data.getStringExtra(SelectNumActivity.KAIKA_PHONE_ID_KEY);
                    String mPhonetype = data.getStringExtra(KAIKA_PHONE_TYPE);
                    String mPhoneLev_mome = data.getStringExtra(KAIKA_NUM_LEV_MEMO);

                    String str[] = new String[3];
                    str[0] = NumPhone;
                    str[1] = mPhoneLev_mome;
                    str[2] = mPhonetype;
                    String strInfo = JSON.toJSONString(str).toString();
                    //提交
                    submitKaiKaChangePhoneNum(specGId, strInfo, order_phone);
                    break;
                case KAIKA_SELECT_FUKA_REQUEST:
                    String fukaNumPhone = data.getStringExtra(KAIKA_PHONE_NUM_KEY);
                    String fukamPhoneNumID = data.getStringExtra(SelectNumActivity.KAIKA_PHONE_ID_KEY);
                    String fukamPhonetype = data.getStringExtra(KAIKA_PHONE_TYPE);
                    String fukamPhoneLev_mome = data.getStringExtra(KAIKA_NUM_LEV_MEMO);

                    String fukastr[] = new String[3];
                    fukastr[0] = fukaNumPhone;
                    fukastr[1] = fukamPhoneLev_mome;
                    fukastr[2] = fukamPhonetype;
                    String fukastrInfo = JSON.toJSONString(fukastr).toString();

                    mAgentWeb.getJsAccessEntrace().quickCallJs(callBackCount, fukastrInfo);
                    break;
                case DETAILS_CHANGESIM_REQUEST_CODE:
                    //选sim卡号返回结果
                    String simNumber = data.getStringExtra(SELECT_SIM_NUM_KEY);
                    submitChangeIccid(simNumber);
                    break;
                case DETAILS_FUKA_REQUEST_CODE:
                    //副卡
                    String fusimNumber = data.getStringExtra(SELECT_SIM_NUM_KEY);
                    mAgentWeb.getJsAccessEntrace().quickCallJs(callBackCount, fusimNumber);
                    break;
                case DETAILS_CHANGE_ZUOJI_REQUEST_CODE:
                    String zuoJiNumber = data.getStringExtra(SELECT_FIXPHONE_NUM_KEY);
                    String number_id = data.getStringExtra(SELECT_FIXPHONE_NUM_ID_KEY);
                    submitChangeZuoJi(zuoJiNumber, number_id);

                    break;
                case HANDSIGN_SELECT_REQUEST:

                    String handSignUrl = data.getStringExtra(HengXiangSign.SIGN_IMG__URL);
                    submitHandSign(handSignUrl, handsigntype);

                    break;
                case HANDSIGN_GETQIANMING_REQUEST:
                    String get_handSignUrl = data.getStringExtra(HengXiangSign.SIGN_IMG__RESULT);
                    mAgentWeb.getJsAccessEntrace().quickCallJs(mcallBack, get_handSignUrl);
                    break;
                default:
                    break;
            }
        }
    }

    /*提交修改的手机号*/
    private void submitPhoneNumber(String specGId, String phoneNum, String numLevMemo, String typePhone) {
        String str[] = new String[3];
        str[0] = phoneNum;
        str[1] = numLevMemo;
        str[2] = typePhone;
        String strInfo = JSON.toJSONString(str).toString();
        App.getApp().getHttpTools().getDetailSubmitPhontNum(specGId, appPhotoUrl, keyWordOrderSn, orderPhone, strInfo, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    DetailSubmitPhotoNumModel changePhone = JSON.parseObject(result, DetailSubmitPhotoNumModel.class);
                    if (changePhone != null) {
                        if (changePhone.getStatus() == 1) {
                            bindData();
                            showToast("" + changePhone.getInfo());
                        } else {
                            showToast("" + changePhone.getInfo());
                        }
                    } else {
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void submitChangeIccid(final String simNumber) {
        App.getApp().getHttpTools().getDetailChangeIccidNum(appPhotoUrl, simNumber, oldIccid, keyWordOrderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    DetailSubmitPhotoNumModel changeIccid = JSON.parseObject(result, DetailSubmitPhotoNumModel.class);
                    if (changeIccid != null) {
                        if (changeIccid.getStatus() == 1) {
                            bindData();
                            showToast("" + changeIccid.getInfo());
                        } else {
                            showToast("" + changeIccid.getInfo());
                        }
                    } else {
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void submitChangeZuoJi(String zuoJiNumber, String number_id) {
        App.getApp().getHttpTools().getDetailChangeZuiJi(appPhotoUrl, oldOrderTel, zuoJiNumber, number_id, keyWordOrderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    DetailSubmitPhotoNumModel changePhone = JSON.parseObject(result, DetailSubmitPhotoNumModel.class);
                    if (changePhone != null) {
                        if (changePhone.getStatus() == 1) {
                            bindData();
                            showToast("" + changePhone.getInfo());
                        } else {
                            showToast("" + changePhone.getInfo());
                        }
                    } else {
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络出错,请检查网络并重试.");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /*    开卡修改手机号码       */
    private void submitKaiKaChangePhoneNum(String specgId, final String Kaika_NumPhone, String order_phone) {
        App.getApp().getHttpTools().getKaiKaDetailChangePhoneNum(order_phone, specgId, appPhotoUrl, Kaika_NumPhone, keyWordOrderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    DetailSubmitPhotoNumModel changePhone = JSON.parseObject(result, DetailSubmitPhotoNumModel.class);
                    if (changePhone != null) {
                        if (changePhone.getStatus() == 1) {
                            bindData();
                            showToast("" + changePhone.getInfo());
                        } else {
                            showToast("" + changePhone.getInfo());
                        }
                    } else {
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络出错,请检查网络并重试.");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void submitHandSign(String handSignUrl, String handsigntype) {
        App.getApp().getHttpTools().getDetailChangeHandSign(handSignUrl, handsigntype, appPhotoUrl, keyWordOrderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    DetailSubmitPhotoNumModel changePhone = JSON.parseObject(result, DetailSubmitPhotoNumModel.class);
                    if (changePhone != null) {
                        if (changePhone.getStatus() == 1) {
                            bindData();
                            showToast("" + changePhone.getInfo());
                        } else {
                            showToast("" + changePhone.getInfo());
                        }
                    } else {
                        showToast("数据出错,请重试");
                    }
                } catch (Exception ex) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络出错,请检查网络并重试.");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            if (1 == msg.what) {
                if (pwdDialog != null && pwdDialog.isAdded()) {
                    pwdDialog.dismiss();
                }
            }
        }

        ;
    };

    /***
     * 开始打开照相机
     */
    private void openCamera() {
        PhotoUtils.takePicture(this, fileUri, CODE_CAMERA_REQUEST);
    }

    /*------------------拍照------------*/
    private void takePhotoImage(int Type) {
        try {
            String sdCardPath = SDCardUtils.getSDCardPathByEnvironment();
            if (TextUtils.isEmpty(sdCardPath)) {
                showToast("SD卡不可用，请检查权限是否给全！");
                return;
            }
            File dirPath = new File(sdCardPath + "/YW189/");
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File filePath = new File(dirPath.getAbsolutePath() + "/zhaopian.jpg");
            if (filePath == null) {
                return;
            }
            fileUri = filePath;
            photoType = Type;
            DingDanDetailsActivityPermissionsDispatcher.NeedPermissionWithCheck(DingDanDetailsActivity.this);
        } catch (Exception ex) {
            ex.printStackTrace();
            showToast("出错：无法创建制定的文件夹，请重试！");
        }
    }

    /***
     * 上传图片 第一步  上传正面图片
     */
    private void submitPic() {

        mYdialog.show();
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1001, file_wenjian.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {
                    if (activityIsDestory()) {
                        return;
                    }
                    updownpic_url = (model.getData().getUrl());
                    updownpic_Repurl = (model.getData().getUrl_rep());
                    mYdialog.dismiss();
                    // Log.e(TAG, "success----橙分期--------"+updownpic_Repurl);
                    // Log.e(TAG, "success----橙分期--------"+mcallBack);
                    showToast("上传成功");
                    mAgentWeb.getJsAccessEntrace().quickCallJs(mcallBack, result);
                }

                @Override
                public void error(int req, String path, String error) {
                    mYdialog.dismiss();
                    showToast(error);
                }
            });
        } catch (Exception ex) {
            if (activityIsDestory()) {
                return;
            }
            mYdialog.dismiss();
            showToast("处理失败，请重试!错误代码:1001");
        }
    }

    /***
     * 上传图片 第一步  上传正面图片
     */
    private void submitKuanDaiPic() {

        mYdialog.show();
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1001, file_wenjian.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {
                    if (activityIsDestory()) {
                        return;
                    }
                    updownpic_url = (model.getData().getUrl());
                    updownpic_Repurl = (model.getData().getUrl_rep());
                    mYdialog.dismiss();
                    showToast("上传成功");
                    App.getApp().getHttpTools().getAddPicSubmit(updownpic_url, PicType, appPhotoUrl, keyWordOrderSn, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            try {
                                AddPhotoModel addPhotoModel = JSON.parseObject(result, AddPhotoModel.class);
                                if (addPhotoModel != null) {
                                    if (addPhotoModel.getStatus() == 1) {
                                        mYdialog.dismiss();
                                        showToast("" + addPhotoModel.getInfo());

                                        bindData();
                                    } else {
                                        mYdialog.dismiss();
                                        showToast("" + addPhotoModel.getInfo() + "");
                                    }
                                } else {
                                    showToast("数据出错,请重试");
                                }
                            } catch (Exception ex) {
                                showToast("数据出错,请重试");
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            if (activityIsDestory()) {
                                return;
                            }
                            mYdialog.dismiss();
                        }

                        @Override
                        public void onCancelled(Callback.CancelledException cex) {
                        }

                        @Override
                        public void onFinished() {
                        }
                    });
                }

                @Override
                public void error(int req, String path, String error) {
                    if (activityIsDestory()) {
                        return;
                    }
                    mYdialog.dismiss();
                    showErrorToast(error);
                }
            });
        } catch (Exception ex) {
            mYdialog.dismiss();
            showToast("处理失败，请重试!错误代码:1001");
        }
    }
}







